package com.example.systemserver.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
//创建一个JSON转换组件，固定写法替换对象针对json格式转换时，将Long类型转为String类型
@JsonComponent
public class JsonConfig {
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule simpleModule = new SimpleModule();
        //将Long类型转为String类型,使用JSON格式时，Long值会丢失精度，使用此方法可解决
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(long.class, ToStringSerializer.instance);
        //注册这个Module到ObjectMapper
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
